package com.mcintyret.site.web.interceptor;

import com.mcintyret.site.context.UserContext;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * User: tommcintyre
 * Date: 3/29/12
 */
@Component
public class JournalDbTransactionInterceptor extends HandlerInterceptorAdapter {

    @Resource(name = "journalSessionFactory")
    private SessionFactory sessionFactory;
    @Resource
    private UserContext userContext;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        if (userContext.isLoggedIn()) {
            sessionFactory.getCurrentSession().beginTransaction();
        }
        return true;
    }

    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        if (userContext.isLoggedIn()) {
            Session sess = sessionFactory.getCurrentSession();
            try {
                if (ex == null) {
                    sess.getTransaction().commit();
                } else {
                    //An exception was thrown during the processing of the request.
                    sess.getTransaction().rollback();
                }

                if (sess.isOpen()) {
                    sess.close();
                }

            } catch (Exception e) {
                throw e;//Let the exception propagate up.
            } finally {
                try {
                    if (sess.isOpen()) {
                        sess.close();
                    }
                } catch (Exception e) {/*do nothing*/}
            }
        }
    }
}


